<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="UTF-8">
    <title>权限管理--右边列表</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta http-equiv="Access-Control-Allow-Origin" content="*">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <link rel="icon" href="/favicon.ico">
    <link rel="stylesheet" href="/layui/css/layui.css" media="all"/>
    <link rel="stylesheet" href="/css/public.css" media="all"/>
    <link rel="stylesheet" href="/layui_ext/dtree/dtree.css" media="all"/>
    <link rel="stylesheet" href="/layui_ext/dtree/font/dtreefont.css" media="all"/>
</head>
<body class="childrenBody">
<!-- 数据表格开始 -->
<div>
    <table class="layui-hide" id="permissionTable" lay-filter="permissionTable"></table>
    <div id="permissionToolBar" style="display: none;">
        <button type="button" lay-event="add" class="layui-btn layui-btn-sm">
            <span class="layui-icon layui-icon-add-1"></span>添加权限
        </button>
    </div>
    <div id="permissionRowBar" style="display: none;">
        <button type="button" lay-event="update" class="layui-btn layui-btn-sm">
            <span class="layui-icon layui-icon-edit"></span>编辑
        </button>
        <button type="button" lay-event="delete" class="layui-btn layui-btn-sm layui-btn-danger">
            <span class="layui-icon layui-icon-delete"></span>删除
        </button>
    </div>
</div>
<!-- 数据表格结束 -->

<!-- 添加和修改的弹出层开始 -->
<div style="display: none; padding: 20px" id="addOrUpdateDiv">
    <form class="layui-form layui-form-pane" id="dataFrm" lay-filter="dataFrm">
        <input type="hidden" name="id">
        <div class="layui-form-item">
            <label class="layui-form-label">关联菜单ID</label>
            <div class="layui-input-block">
                <input type="hidden" name="menuId" id="menuId" lay-verify="required">
                <ul id="menuTree" class="dtree" data-id="0"></ul>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">权限名称</label>
            <div class="layui-input-block">
                <input type="text" name="name" lay-verify="required" placeholder="请输入权限名称" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">权限标识</label>
            <div class="layui-input-block">
                <input type="text" name="code" lay-verify="required" placeholder="如：user:view" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">权限类型</label>
            <div class="layui-input-block">
                <select name="type" lay-verify="required">
                    <option value="menu">菜单权限</option>
                    <option value="button">操作权限</option>
                    <option value="api">API权限</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">是否可用</label>
            <div class="layui-input-block">
                <input type="radio" name="available" value="1" title="可用" checked>
                <input type="radio" name="available" value="0" title="禁用">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block" style="text-align: center;">
                <button type="button" class="layui-btn" lay-submit lay-filter="doSubmit">
                    <span class="layui-icon layui-icon-add-1"></span>提交
                </button>
                <button type="reset" class="layui-btn layui-btn-warm">
                    <span class="layui-icon layui-icon-refresh-1"></span>重置
                </button>
            </div>
        </div>
    </form>
</div>
<!-- 添加和修改的弹出层结束 -->
<script type="text/javascript" src="/layui/layui.js"></script>
<script th:inline="javascript">
    layui.extend({
        dtree: '/layui_ext/dtree/dtree'
    }).use(['jquery', 'form', 'table', 'layer', 'dtree'], function () {
        var $ = layui.jquery;
        var form = layui.form;
        var table = layui.table;
        var layer = layui.layer;
        var dtree = layui.dtree;

        // 初始化数据表格
        var tableIns = table.render({
            elem: '#permissionTable',
            url: '/permission/list',
            toolbar: '#permissionToolBar',
            title: '权限数据表',
            height: 'full-40',
            page: true,
            cols: [[
                {field: 'id', title: 'ID', align: 'center'},
                {field: 'menuName', title: '关联菜单', align: 'center'},
                {field: 'name', title: '权限名称', align: 'center'},
                {field: 'code', title: '权限标识', align: 'center'},
                // {
                //     field: 'type',
                //     title: '类型',
                //     width: 120,
                //     templet: function(d) {
                //         return {'menu':'菜单','button':'按钮','api':'接口'}[d.type];
                //     }
                // },
                {field: 'available', title: '状态', width: 100, templet: function (d) {
                        return d.available == 1 ? '<font color="blue">可用</font>' : '<font color="red">禁用</font>';
                    }},
                {fixed: 'right', title: '操作', toolbar: '#permissionRowBar', width: 200}
            ]],
            where: { menuId: null}
        });

        // 初始化菜单树
        var menuTree = dtree.renderSelect({
            elem: "#menuTree",
            dataStyle: "layuiStyle",
            dataFormat: "list",
            response: {message: "msg", statusCode: 0},
            method:"GET",
            url: "/menu/tree",
            line: true,
            icon: ["2", "-1"],
            initLevel: 2
        });

        // 监听菜单树选择
        dtree.on("node(menuTree)", function (obj) {
            $("#menuId").val(obj.param.nodeId);
            form.render();
        });

        // 提供给左侧树的刷新方法
        window.reloadTable = function (menuId) {
            tableIns.reload({
                where: {
                    menuId: menuId // 确保参数名与后端一致
                },
                page: { curr: 1 }
            });
        };

        // 工具栏事件
        table.on('toolbar(permissionTable)', function (obj) {
            if (obj.event === 'add') {
                openAddLayer();
            }
        });

        // 行工具事件
        table.on('tool(permissionTable)', function (obj) {
            var data = obj.data;
            switch (obj.event) {
                case 'update':
                    openUpdateLayer(data);
                    break;
                case 'delete':
                    deletePermission(data);
                    break;
            }
        });

        var mainIndex, url;

        // 打开添加层
        function openAddLayer() {
            mainIndex = layer.open({
                type: 1,
                content: $("#addOrUpdateDiv"),
                area: ['700px', '500px'],
                title: '添加权限',
                success: function () {
                    $("#dataFrm")[0].reset();
                    $("#menuId").val("");
                    menuTree.reload();
                    url = "/permission/add";
                }
            });
        }

        // 打开修改层
        function openUpdateLayer(data) {
            mainIndex = layer.open({
                type: 1,
                content: $("#addOrUpdateDiv"),
                area: ['700px', '500px'],
                title: '修改权限',
                success: function () {
                    $("#menuId").val(data.menuId);
                    form.val("dataFrm", data);
                    dtree.dataInit("menuTree", data.menuId);
                    dtree.selectVal("menuTree");
                    url = "/permission/update";
                }
            });
        }

        // 提交表单
        form.on('submit(doSubmit)', function (data) {
            $.ajax({
                url: url,
                type: "POST",
                contentType: "application/json",
                data: JSON.stringify(data.field),
                success: function (res) {
                    layer.msg(res.msg);
                    if (res.code === 200) {
                        tableIns.reload();
                        window.parent.left.permissionTree.reload();
                        layer.close(mainIndex);
                    }
                },
                error: function (xhr) {
                    layer.msg("操作失败: " + xhr.statusText);
                }
            });
            return false;
        });

        // 删除权限（增强版）
        function deletePermission(data) {
            // 1. 检查是否被角色引用
            $.post("/permission/checkRoleRef", {id: data.id}, function (res) {
                if (res.hasRef) {
                    layer.msg("该权限已被角色引用，无法删除！");
                    return;
                }

                // 2. 确认删除
                layer.confirm('确定删除【' + data.name + '】权限吗？', function (index) {
                    $.ajax({
                        url: "/permission/delete",
                        type: "DELETE",
                        data: {id: data.id},
                        success: function (res) {
                            layer.msg(res.msg);
                            if (res.code === 200) {
                                tableIns.reload();
                                window.parent.left.permissionTree.reload();
                            }
                            layer.close(index);
                        }
                    });
                });
            });
        }

        // 提供给左侧树的刷新方法
        window.reloadTable = function (menuId) {
            tableIns.reload({
                where: {menuId: menuId},
                page: {curr: 1}
            });
        };
    });
</script>
</body>
</html>